import type { BasicUserInfo, Recordable, UserInfo } from '@vben/types';

import type { AccountLoginReq, EmailLoginReq, PhoneLoginReq } from '#/api/auth';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { ElNotification } from 'element-plus';
import { defineStore } from 'pinia';

import {
  accountLogin,
  emailLogin,
  getUserInfo,
  logout as logoutApi,
  phoneLogin,
  socialAuth,
  socialLogin,
} from '#/api/auth';
import { AuthTypeConstants } from '#/api/auth/type';
import { $t } from '#/locales';

// 定义登录类型
type LoginType = 'ACCOUNT' | 'EMAIL' | 'PHONE' | 'SOCIAL';

// 通用登录参数处理函数
const createLoginParams = (params: any, authType: string) => ({
  ...params,
  authType,
  clientId: import.meta.env.VITE_CLIENT_ID,
});

// 登录函数映射
const loginApiMap: Record<LoginType, (params: any) => Promise<any>> = {
  ACCOUNT: (params: any) =>
    accountLogin(
      createLoginParams(params, AuthTypeConstants.ACCOUNT) as AccountLoginReq,
    ),
  EMAIL: (params: any) =>
    emailLogin(
      createLoginParams(params, AuthTypeConstants.EMAIL) as EmailLoginReq,
    ),
  PHONE: (params: any) =>
    phoneLogin(
      createLoginParams(params, AuthTypeConstants.PHONE) as PhoneLoginReq,
    ),
  SOCIAL: (params: any) =>
    socialLogin(createLoginParams(params, AuthTypeConstants.SOCIAL)),
};

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   * @param type 登录类型：'ACCOUNT' | 'EMAIL' | 'PHONE' | 'SOCIAL'
   * @param onSuccess 登录成功函数
   */
  async function authLogin(
    params: Recordable<any>,
    type: LoginType = 'ACCOUNT',
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    const userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;

      // 调用对应的登录API
      const loginResult = await loginApiMap[type](params);

      const { token: accessToken } = loginResult;

      // 如果成功获取到 accessToken
      if (accessToken) {
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        const userInfo = await getUserInfo();

        userStore.setUserInfo(userInfo);
        accessStore.setRoles(userInfo.roles);
        accessStore.setPermissions(userInfo.permissions);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(DEFAULT_HOME_PATH);
        }

        if (userInfo?.nickname) {
          ElNotification({
            message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.nickname}`,
            title: $t('authentication.loginSuccess'),
            type: 'success',
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  /**
   * 社交账号认证
   * @param source 社交账号来源
   */
  async function authSocial(source: string) {
    return socialAuth(source);
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: BasicUserInfo | null = null;
    userInfo = await getUserInfo();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    authSocial,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
